package com.hzzftech.watchdog.busi.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.hzzftech.watchdog.busi.core.executor.starter.KettleEnvironmentStarter;
import com.hzzftech.watchdog.busi.domain.RJob;
import com.hzzftech.watchdog.busi.utils.PageInfoUtils;
import com.hzzftech.watchdog.common.utils.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.repository.LongObjectId;
import org.pentaho.di.repository.kdr.KettleDatabaseRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hzzftech.watchdog.busi.mapper.RTransformationMapper;
import com.hzzftech.watchdog.busi.domain.RTransformation;
import com.hzzftech.watchdog.busi.service.IRTransformationService;
import com.hzzftech.watchdog.common.core.text.Convert;

/**
 * 数据库资源库_transService业务层处理
 * 
 * @author kt-watchdog
 * @date 2022-01-27
 */
@Service
public class RTransformationServiceImpl implements IRTransformationService 
{

    private static Logger logger = LoggerFactory.getLogger(RTransformationServiceImpl.class);
    @Autowired
    private RTransformationMapper rTransformationMapper;

    /**
     * 查询数据库资源库_trans
     * 
     * @param idTransformation 数据库资源库_trans主键
     * @return 数据库资源库_trans
     */
    @Override
    public RTransformation selectRTransformationByIdTransformation(Long idTransformation)
    {
        return rTransformationMapper.selectRTransformationByIdTransformation(idTransformation);
    }

    @Override
    public Integer selectRTransformationCount(RTransformation rTransformation) {
        KettleDatabaseRepository repository = (KettleDatabaseRepository) KettleEnvironmentStarter.instance.getRepository();
        try {
            String sql = "select count(*) from r_transformation";
            if (StringUtils.isNotEmpty(rTransformation.getNAME())) {
                sql += " where `NAME` like '%" + rTransformation.getNAME() + "%'";
            }
            Result result = repository.getDatabase().execStatement(sql);
            List<RowMetaAndData> rows = result.getRows();
            if (CollectionUtils.isNotEmpty(rows)) {
                return rows.get(0).getInteger(0).intValue();
            }
        } catch (Exception e) {
            logger.error("查询JOB列表信息失败", e);
            throw new RuntimeException("查询JOB列表信息失败",e);
        }
        return null;
    }

    /**
     * 查询数据库资源库_trans列表
     * 
     * @param rTransformation 数据库资源库_trans
     * @return 数据库资源库_trans
     */
    @Override
    public List<RTransformation> selectRTransformationList(RTransformation rTransformation,  Integer pgNum, Integer pgSize, String orderBy)
    {
        KettleDatabaseRepository repository = (KettleDatabaseRepository) KettleEnvironmentStarter.instance.getRepository();
        try {
            String sql = "select count(*) from r_transformation";
            if (StringUtils.isNotEmpty(rTransformation.getNAME())) {
                sql += " where `NAME` like '%" + rTransformation.getNAME()+"%'";
            }
            sql += " limit " + (pgNum - 1) * pgSize +"," + pgSize;
            if (StringUtils.isNotEmpty(orderBy)) {
                sql += orderBy; // " order by MODIFIED_DATE desc"
            }
            Result result = repository.getDatabase().execStatement(sql);
            List<RowMetaAndData> rows = result.getRows();
            if (CollectionUtils.isNotEmpty(rows)) {
                List<RTransformation> rTransformationList = new ArrayList<>(20);
                for (RowMetaAndData rowMetaAndData : rows) {
                    RTransformation t = new RTransformation();
                    Long ID_TRANSFORMATION = rowMetaAndData.getInteger(0);
                    Long IDDIRECTORY = rowMetaAndData.getInteger(1);
                    String NAME = rowMetaAndData.getString(2, "");
                    String DESCRIPTION = rowMetaAndData.getString(3, "");
                    String EXTENDED_DESCRIPTION = rowMetaAndData.getString(4, "");
                    String TRANS_VERSION = rowMetaAndData.getString(5, "");
                    Long TRANS_STATUS = rowMetaAndData.getInteger(6);
                    Long ID_STEP_READ = rowMetaAndData.getInteger(7);
                    Long ID_STEP_WRITE = rowMetaAndData.getInteger(8);
                    Long ID_STEP_INPUT = rowMetaAndData.getInteger(9);
                    Long ID_STEP_OUTPUT = rowMetaAndData.getInteger(10);
                    Long ID_STEP_UPDATE = rowMetaAndData.getInteger(11);
                    Long ID_DATABASE_LOG = rowMetaAndData.getInteger(12);
                    String TABLE_NAME_LOG = rowMetaAndData.getString(13, "");
                    Integer USE_BATCHID = rowMetaAndData.getString(14, "") == null ? null : rowMetaAndData.getInteger(14).intValue() ;
                    Integer USE_LOGFIELD = rowMetaAndData.getString(15, "") == null ? null : rowMetaAndData.getInteger(15).intValue();
                    Long ID_DATABASE_MAXDATE = rowMetaAndData.getInteger(16);
                    String TABLE_NAME_MAXDATE = rowMetaAndData.getString(17, "");
                    String FIELD_NAME_MAXDATE = rowMetaAndData.getString(18, null);
                    Long OFFSET_MAXDATE = rowMetaAndData.getInteger(19);
                    Long DIFF_MAXDATE = rowMetaAndData.getInteger(20);
                    String CREATED_USER = rowMetaAndData.getString(21, "");
                    Date CREATED_DATE = rowMetaAndData.getDate(22, null);
                    String MODIFIED_USER = rowMetaAndData.getString(23, "");
                    Date MODIFIED_DATE = rowMetaAndData.getDate(24, null);
                    Long SIZE_ROWSET = rowMetaAndData.getInteger(25);
                    t.setIdTransformation(ID_TRANSFORMATION);
                    t.setIdDirectory(IDDIRECTORY);
                    t.setNAME(NAME);
                    t.setDESCRIPTION(DESCRIPTION);
                    t.setExtendedDescription(EXTENDED_DESCRIPTION);
                    t.setTransVersion(TRANS_VERSION);
                    t.setTransStatus(TRANS_STATUS);
                    t.setIdStepRead(ID_STEP_READ);
                    t.setIdStepWrite(ID_STEP_WRITE);
                    t.setIdStepInput(ID_STEP_INPUT);
                    t.setIdStepOutput(ID_STEP_OUTPUT);
                    t.setIdStepUpdate(ID_STEP_UPDATE);
                    t.setIdDatabaseLog(ID_DATABASE_LOG);
                    t.setTableNameLog(TABLE_NAME_LOG);
                    t.setUseBatchid(USE_BATCHID);
                    t.setUseLogfield(USE_LOGFIELD);
                    t.setIdDatabaseMaxdate(ID_DATABASE_MAXDATE);
                    t.setTableNameMaxdate(TABLE_NAME_MAXDATE);
                    t.setFieldNameMaxdate(FIELD_NAME_MAXDATE);
                    t.setOffsetMaxdate(OFFSET_MAXDATE);
                    t.setDiffMaxdate(DIFF_MAXDATE);
                    t.setCreatedUser(CREATED_USER);
                    t.setCreatedDate(CREATED_DATE);
                    t.setModifiedUser(MODIFIED_USER);
                    t.setModifiedDate(MODIFIED_DATE);
                    t.setSizeRowset(SIZE_ROWSET);
                    t.setDirectoryPath(repository.findDirectory(new LongObjectId(ID_TRANSFORMATION)).getPath());
                    rTransformationList.add(t);
                }
                return rTransformationList;
            }
        } catch (Exception e) {
            logger.error("查询JOB列表信息失败", e);
            throw new RuntimeException("查询JOB列表信息失败",e);
        }
        return new ArrayList<>(0);
    }

    /**
     * 新增数据库资源库_trans
     * 
     * @param rTransformation 数据库资源库_trans
     * @return 结果
     */
    @Override
    public int insertRTransformation(RTransformation rTransformation)
    {
        return rTransformationMapper.insertRTransformation(rTransformation);
    }

    /**
     * 修改数据库资源库_trans
     * 
     * @param rTransformation 数据库资源库_trans
     * @return 结果
     */
    @Override
    public int updateRTransformation(RTransformation rTransformation)
    {
        return rTransformationMapper.updateRTransformation(rTransformation);
    }

    /**
     * 批量删除数据库资源库_trans
     * 
     * @param idTransformations 需要删除的数据库资源库_trans主键
     * @return 结果
     */
    @Override
    public int deleteRTransformationByIdTransformations(String idTransformations)
    {
        return rTransformationMapper.deleteRTransformationByIdTransformations(Convert.toStrArray(idTransformations));
    }

    /**
     * 删除数据库资源库_trans信息
     * 
     * @param idTransformation 数据库资源库_trans主键
     * @return 结果
     */
    @Override
    public int deleteRTransformationByIdTransformation(Long idTransformation)
    {
        return rTransformationMapper.deleteRTransformationByIdTransformation(idTransformation);
    }
}
